<template>
  <div class="exam-container">
    <!-- 测评列表 -->
    <div class="exam-list">
      <el-card
          v-for="(exam,index) in exams"
          :key="exam.id"
          class="exam-card"
          shadow="hover"
      >
        <!-- 卡片内容 -->
        <div class="card-content">
          <!-- 封面图区域 -->
          <div class="cover">
            <img v-if="exam.paperImage" :src="exam.paperImage" alt="测评封面">
            <div v-else class="cover-placeholder">
              <el-icon :size="40">
                <Picture/>
              </el-icon>
            </div>
          </div>

          <!-- 测评信息 -->
          <div class="meta">
            <h3 class="title"><b>{{ exam.title }}</b></h3>
            <p class="desc">{{ exam.description }}</p>

            <div class="info">
              <span class="time">
                <el-icon><Clock/></el-icon>
                {{ exam.timeLimit === null ? "不限时" : `${exam.timeLimit}分钟` }}
              </span>
              <span class="count">
                <el-icon><Document/></el-icon>
                {{ exam.questionTotal }}题
              </span>
            </div>

            <div class="footer">
              <el-tag :type="statusType[exam.status]">
                {{ statusText(exam.status) }}
                <span v-if="exam.status === '3'">（{{ exam.endReason }}）</span>
              </el-tag>

              <el-button
                  v-if="exam.status === '0' || exam.status === '1'"
                  type="primary"
                  size="small"
                  @click.stop="startExam(exam.id)"
              >
                立即测评
              </el-button>

              <el-button
                  type="success"
                  size="small"
                  v-if="exam.status==='2'"
                  @click="handleExamClick(exam.id)"
              >
                查看报告
              </el-button>
              <!-- 已超时 -->
              <el-tooltip
                  v-if="exam.status === '3'"
                  content="该测评已超时结束，可查看试卷信息但无法作答"
                  placement="top"
              >
                <el-button
                    type="info"
                    size="small"
                    :disabled="true"
                >
                  查看试卷
                </el-button>
              </el-tooltip>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>

</template>

<script setup>
import {ref, computed, onMounted} from 'vue'
import {Clock, Document, Picture} from '@element-plus/icons-vue'
import {paperPreview} from "@/api/assessments/assessments.js";
import {checkStatus} from "@/api/exam/paper.js";
import {checkRecord} from "@/api/record/record.js";

const {proxy} = getCurrentInstance()
const {exam_status} = proxy.useDict("exam_status");

const exams = ref([])

// 状态类型映射
const statusType = computed(() => ({
  0: 'primary',   // 未开始
  1: 'success',   // 进行中
  2: 'info',      // 已完成
  3: 'danger'     // 已结束（超时）
}))

// 状态文本映射
function statusText(status) {
  for (let i = 0; i < exam_status.value.length; i++) {
    if (exam_status.value[i].value === status) {
      return exam_status.value[i].label;
    }
  }
}

// 查看测评详情事件
const handleExamClick = (id) => {
  console.log('查看测评详情:', id)
  proxy.$router.push({
    path: '/result',
    query: {  // 使用 query 传参
      paperId: id,
      delFlag: '0',
      recordId: null,
    }
  })
}

// 开始测评
const startExam = (id) => {
  // 校验逻辑
  checkStatus(id).then(res => {
    if (res.code === 200) {
      // 说明测评可以开始
      proxy.$router.push({
        path: '/examPage',
        query: {  // 使用 query 传参
          paperId: id,
        }
      })
    } else {
      proxy.$message.error(res.message)
    }
  })
}

// 获取测评卷预览信息
async function getPaperReview() {
  const response = await paperPreview();
  const paperList = response.data;

  const processedPapers = await Promise.all(paperList.map(async (paper) => {
    // 处理时间限制状态
    if (paper.startTime) {
      const startTime = new Date(paper.startTime).getTime();
      if (Date.now() > startTime) {
        return {
          ...paper,
          status: '3',
          endReason: '超时自动结束',
          canView: await checkHasRecord(paper.id) // 检查是否有历史记录
        }
      }
    }

    // 处理用户记录状态
    try {
      const res = await checkRecord(paper.id);

      if (!res) { // 对应后端返回null的情况
        paper.status = '2'; // 存在记录但状态不是进行中，设为已完成
      } else if (res.code === 200) {
        if (res.data) {
          paper.status = '1'; // 存在进行中的记录
        } else {
          paper.status = '0'; // 无记录
        }
      }
    } catch (e) {
      console.error("记录检查失败:", e);
      paper.status = '0'; // 默认未开始
    }

    return paper;
  }));
  exams.value = processedPapers;
}

// 检查是否存在记录
const checkHasRecord = async (id) => {
  try {
    const res = await checkRecord(id);
    return res.data !== null;
  } catch {
    return false;
  }
}

onMounted(() => {
  getPaperReview();
})
</script>

<style scoped>
.el-button.is-disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

/* 超时卡片特殊样式 */
.exam-card[data-status="3"] {
  position: relative;
  opacity: 0.9;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    z-index: 1;
  }

  .footer {
    position: relative;
    z-index: 2;
  }
}

.exam-container {
  padding: 20px;
  background: #f5f7fa;
}

/* Flex 布局容器 */
.exam-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px; /* 卡片间距 */
}

/* 卡片样式 */
.exam-card {
  flex: 1 1 calc(25% - 20px); /* 默认4列 */
  min-width: 180px; /* 最小宽度 */
  max-width: 600px; /* 最大宽度 */
  cursor: pointer;
  transition: transform 0.3s;

  &:hover {
    transform: translateY(-5px);
  }
}

/* 卡片内容布局 */
.card-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 封面图区域 */
.cover {
  height: 300px;
  background: #f0f2f5;
  border-radius: 5px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .cover-placeholder {
    color: #c0c4cc;
  }
}

/* 元信息区域 */
.meta {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;

  .title {
    margin: 0 0 10px;
    font-size: 16px;
    color: #303133;
  }

  .desc {
    flex: 1;
    margin: 0 0 15px;
    font-size: 13px;
    color: #606266;
    line-height: 1.5;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }

  .info {
    display: flex;
    gap: 15px;
    margin-bottom: 15px;
    font-size: 12px;
    color: #909399;

    .el-icon {
      margin-right: 5px;
    }
  }

  .footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .exam-card {
    flex-basis: calc(33.33% - 20px); /* 3列 */
  }
}

@media (max-width: 992px) {
  .exam-card {
    flex-basis: calc(50% - 20px); /* 2列 */
  }
}

@media (max-width: 768px) {
  .exam-card {
    flex-basis: 100%; /* 1列 */
  }
}
</style>
